package cn.zou.blog.controller;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.nio.channels.FileChannel.MapMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import cn.zou.blog.entry.Article;
import cn.zou.blog.service.ArticleService;
import cn.zou.core.contant.Contant;
import cn.zou.core.json.JSONUtils;
import cn.zou.core.json.ResponseUtils;
import cn.zou.core.page.Page;

/**
 * 文章管理类
 * @author zoujing
 *
 */
@Controller
@RequestMapping("/article")
public class ArticleController  {
	private static Logger logger=Logger.getLogger(ArticleController.class);
	@Autowired
	private ArticleService articleService;
	@RequestMapping("/admin/toArticleUI.shtml")
	public String toArticleUI(@RequestParam(required=false)String serach, HttpServletRequest request,HttpServletResponse response,ModelMap map,Page<Article> page){
			if(page==null){
				return null;
			}else{
				if(StringUtils.isNotBlank(serach)){
					page.setSerach(serach);
				}else{
					page.setSerach(null);
				}
				
				page = (Page<Article>) articleService.findByTitle(page);
				map.addAttribute("page", page);
				map.addAttribute("articles", "articles");
				map.addAttribute("articleType", Article.INFO_TYPE_MAP);
				return "admin/article/amdin_ArticleManagerUI";
			}
			
	}
	@RequestMapping("/admin/toAddUI.shtml")
	public String toAddUI(ModelMap map){
		map.addAttribute("articleType", Article.INFO_TYPE_MAP);
		return "admin/article/admin_ArticleAddUI";
	}
	@RequestMapping("/admin/Addarcicle.shtml")
	public String add(@RequestParam(required = false) MultipartFile pic,ModelMap model,Article article,HttpServletRequest request,HttpServletResponse response){
		try {
			if(article!=null &&StringUtils.isNotBlank(article.getTitle())){
				if(pic!=null){
					//如果上传的图片补位空的话
					InputStream inputStream = pic.getInputStream();
					//获取扩展名
					String ext=FilenameUtils.getExtension(pic.getOriginalFilename());
					String newDate = new SimpleDateFormat("yyyyMMddHHmmssSSSSS").format(new Date()).toString();
					
					String filename=newDate+"."+ext;
					String RePath=request.getSession().getServletContext().getRealPath("/upload/article");
					FileUtils.copyInputStreamToFile(inputStream, new File(RePath,filename));
					article.setImageUrl("article/"+filename);	
				}
				//为期添加ID
				//设置浏览次数为0
				article.setCurrnt(new Long(0));
				article.setId(UUID.randomUUID().toString().replace("-", ""));
				try {
					articleService.addArticle(article,request);
				} catch (Exception e) {
					try {
						request.setAttribute("error", "你可能已经提交过一次该文章标题了或者与他人标题重复");
						request.getRequestDispatcher("toAddUI.shtml").forward(request, response);
						return null;
					} catch (ServletException e1) {
						// TODO 自动生成的 catch 块
						e1.printStackTrace();
					}
				}
				return "redirect:toArticleUI.shtml";
			}else{
				logger.info("添加的文章确错误");
				return null;
			}
			
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			logger.error(e.getMessage());
			return null;
		}finally{
			if(pic!=null){
				try {
					if(pic.getInputStream()!=null){
						pic.getInputStream().close();
					}
				} catch (IOException e) {
					// TODO 自动生成的 catch 块
					e.printStackTrace();
				}
			}
		}	
	}
	/**
	 * 跳转编辑页面
	 * @param title 搜索条件
	 * @param pageNo 当前页面
	 * @param map 传递参数值
	 * @return
	 */
	@RequestMapping("/admin/doEditUI.shtml")
	public String doEditUI(@RequestParam(required=false)String serach,@RequestParam(required=false)int pageNo,ModelMap map,@RequestParam(required=false)String id){
		//查找出当前文章
		if(StringUtils.isNotBlank(id)){
			Article article= articleService.findById(id);
			map.addAttribute("article",article);
			
		}
		map.addAttribute("articleType", Article.INFO_TYPE_MAP);
		map.addAttribute("serach", serach);
		map.addAttribute("pageNo", pageNo);
		
		return "admin/article/admin_ArticleEditUI";
	}
	/**
	 * 文章修改
	 * @param serach
	 * @param pageNo
	 * @param map
	 * @param article
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping("/admin/Editarcicle.shtml")
	public String Edit(@RequestParam(required = false) MultipartFile pic,ModelMap map,@RequestParam(required = false)String state,
			@RequestParam(required = false) String id,@RequestParam(required = false) String title,@RequestParam(required = false) String content,@RequestParam(required = false) String create,@RequestParam(required = false) Date modifyTime,@RequestParam(required = false) String type,@RequestParam(required = false) String imageUrl,
			String serach,String pageNo,HttpServletRequest request,HttpServletResponse response){
		try {
			if(!StringUtils.isNotBlank(title)){
				request.setAttribute("error", "你可能已经提交过一次该文章标题了或者与他人标题重复");
				request.getRequestDispatcher("doEditUI.shtml").forward(request, response);
				return null;
			}else{
				Article article=new Article();
				article.setId(id);
				article.setContent(content);
				article.setTitle(title);
				article.setCreate(create);
				article.setState(state);
				article.setModifyTime(modifyTime);
				article.setImageUrl(imageUrl);
				article.setType(type);
				if(pic.getSize()>0){
					//如果上传的图片补位空的话
					InputStream inputStream = pic.getInputStream();
					//获取扩展名
					String ext=FilenameUtils.getExtension(pic.getOriginalFilename());
					String newDate = new SimpleDateFormat("yyyyMMddHHmmssSSSSS").format(new Date()).toString();
					String filename=newDate+"."+ext;
					String RePath=request.getSession().getServletContext().getRealPath("/upload/article");
					FileUtils.copyInputStreamToFile(inputStream, new File(RePath,filename));
					//删除原来的图片
					String oldPath=request.getSession().getServletContext().getRealPath("/upload/"+article.getImageUrl());
					FileUtils.deleteQuietly(new File(oldPath));
					article.setImageUrl("article/"+filename);	
				}
				articleService.updateArticleById(article,request);
				
			}
		} catch (Exception e) {
			try {
				request.setAttribute("error", "你可能已经提交过一次该文章标题了或者与他人标题重复");
				request.getRequestDispatcher("doEditUI.shtml").forward(request, response);
				return null;
			} catch (Exception e1) {
				// TODO 自动生成的 catch 块
				e1.printStackTrace();
			}
		}
		map.addAttribute("serach", serach);
		map.addAttribute("pageNo", pageNo);
		return "redirect:toArticleUI.shtml";
	}
	/**
	 * 删除文章
	 * @return
	 */
	@RequestMapping("/admin/deleteArticle.shtml")
	public String deleteArticle(HttpServletRequest request,String serach,int pageNo,ModelMap map,String id){
		articleService.deleteArticleByid(id,request);
		map.addAttribute(serach, serach);
		map.addAttribute("pageNo", pageNo);
		return "redirect:toArticleUI.shtml";
	}
	/**
	 * 批量删除
	 * @param request
	 * @param serach
	 * @param pageNo
	 * @param map
	 * @param selectedRow
	 * @return
	 */
	@RequestMapping("/admin/deleteAllArticle")
	public String deletArticle(HttpServletRequest request,String serach,int pageNo,ModelMap map,String[] selectedRow){
		for(String id:selectedRow){
			articleService.deleteArticleByid(id,request);
		}
		map.addAttribute(serach, serach);
		map.addAttribute("pageNo", pageNo);
		return "redirect:toArticleUI.shtml";
	}
	@RequestMapping("upadteStateArticle.shtml")
	public void upadteStateArticle(HttpServletRequest request,HttpServletResponse response,String id,String state){
		articleService.upadteStateArticle(id,state,request);
		response.setContentType("text/html");
		try {
			ServletOutputStream outputStream = response.getOutputStream();
			outputStream.write("更新状态成功".getBytes("utf-8"));
			outputStream.close();
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		
	}
	/**
	 * 根据ID查询文章
	 * @param id
	 * @param request
	 * @param map
	 * @return
	 */
	@RequestMapping("/toArticle.shtml")
	public String toArticle(@RequestParam(required=false)String id,HttpServletRequest request,ModelMap map){
		Article article= articleService.findByIdInLuncene(id,request);
		map.addAttribute("article", article);
		return "article";
	}
	@RequestMapping("/newArticle.shtml")
	public void newArticle(HttpServletResponse response){
		List<Article> list= articleService.findnewArticle();
		Map map=new HashMap<String, Object>();
		map.put("msg", "成功");
		map.put("list", list);
		String json=JSONUtils.objectTwoJson(map);
		System.out.println(json);
		ResponseUtils.renderJson(response, json);
	}
}
